#!/usr/bin/node

// async https://github.com/caolan/async
// q https://github.com/kriskowal/q
// request https://github.com/request/request

var Q = require('q');
var async = require('async');
var request = require('request');
var fs = require('fs');
var path=require('path');

request
	.get('http://www.baidu.com/img/bdlogo.png')
	.on('response', function(response) {
		console.log(response.statusCode) // 200
		console.log(response.headers['content-type']) // 'image/png'
	})
	// .pipe(request.put('http://mysite.com/img.png'))
	.pipe(fs.createWriteStream(path.resolve(__dirname,'img.png')));

// q
var readFile = Q.denodeify(fs.readFile);
var req_get = Q.denodeify(request);
var req_post = Q.denodeify(request.post);
readFile(__filename, 'utf8')
	.then(function(data) {
		console.log('q done 1,now get');
		return req_get('http://www.baidu.com');
	})
	.then(function(response) {
		console.log('q done 2,now post');
		return req_post('http://www.baidu.com',{form:{a:1}});
	})
	.then(function(res){
		console.log('q done 3,now get an invalid url');
		return req_get('abc.com')
	})
	.catch(function(err) {
		console.log('q ',err);
	})
	.done();


// async
async.waterfall([
	function(next){
		fs.readFile(__filename,'utf8',function(err,data){
			next(err,data);
		});
	},
	function(fileContent,next){
		console.log('async read file done');
		request.get('http://www.baidu.com',function(err,res,data1){
			next(err,res,data1);
		});
	},
	function(res,data,next){
		console.log('async req1 done');
		request.post('http://www.baidu.com',{form:{a:1}},function(err,res,data2){
			next(err,res,data2);
		});
	},
	function(res,data,next){
		console.log('async req2 done');
		request('abc.com',function(err,res,data3){
			next(err,res,data3); // this time err will not be null
		});
	},
],function(err,res,data){
	if(err){
		console.log('async ',err);
	}
});


// post json
// http://stackoverflow.com/questions/8675688/send-content-type-application-json-post-with-node-js
// var request = require('request');

// var options = {
//   uri: 'https://www.googleapis.com/urlshortener/v1/url',
//   method: 'POST',
//   json: {
//     "longUrl": "http://www.google.com/"
//   }
// };

// request(options, function (error, response, body) {
//   if (!error && response.statusCode == 200) {
//     console.log(body.id) // Print the shortened url.
//   }
// });